<template>
  <!--订单号，订单金额，订单优惠，金额小计
  实付金额，付款方式-->
  <section>
    <el-table :data="checkOrders" show-summary :summary-method="getSummaries">
      <el-table-column type="index"/>
      <el-table-column label="订单号" prop="id"/>
      <el-table-column label="订单金额" prop="totalPrice"/>
      <el-table-column label="订单优惠" prop="salePrice"/>
      <el-table-column label="订单实付" prop="payPrice"/>
    </el-table>
    <el-row style="padding:10px 0;" type="flex">
      <el-col :span="18" style="border:0px solid red">
        <el-select v-model="selPayType" size="small" placeholder="请选择付款方式">
          <el-option v-for="payType in payTypes" :key="payType.code" :label="payType.txt" :value="payType.code">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6" style="border:0px solid fuchsia;margin-left: 10px">
        <el-button v-if="selPayType !== 'balance' && selPayType" @click="btnCreatePay" type="primary" size="small">确定支付</el-button>
        <el-button v-else @click="btnCreatePay" type="primary" size="small" :disabled="(currPay.balanceMoney - currPay.payPrice) <0">
          确定支付
        </el-button>
      </el-col>
    </el-row>
    <el-row v-if="selPayType === 'balance'">
      <el-row>总额：{{currPay.payPrice}}</el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="10">现金：
          <el-input size="mini" style="width: 160px" v-model="currPay.balanceMoney" @change="getNumber(currPay.balanceMoney)" type="number"/>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px">
        <el-col :span="2">找零：</el-col>
        <el-col :span="10" v-show="currPay.balanceMoney">{{(currPay.balanceMoney-currPay.payPrice).toFixed(2)}}元</el-col>
      </el-row>
    </el-row>
  </section>
</template>

<script>
  import errHandler from '@/assets/errHandler'
  import { mapActions,mapGetters} from 'vuex'
  export default {
    name: "showPay",
    props: ['pay','orders'],
    data(){
      return{
        checkOrders:[],
        selPayType:null,
        payTypes:[
          {txt:'货到付款',code:'cod'},
          {txt:'微信支付',code:'wxpay'},
          {txt:'微信扫码',code:'wxpay_micropay'},
          {txt:'支付宝',code:'alipay'},
          {txt:'现金支付',code:'balance'},
          {txt:'银行卡',code:'bank_card'},
          ],
        currPay:{},
        accountList:null,
      }
    },
    computed:{
      ...mapGetters(['department'])
    },
    created(){
      console.log('pay---order----showPay----',this.pay,this.orders)
      this.init()
    },
    watch:{
      pay(nv,ov){
        this.init()
      }
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      getNumber(e){
        console.log('fixed----',e)
        e=Number(e).toFixed(2)
        console.log('????',e)
        // return e
      },
      init(){
        console.log(this.pay)
        this.currPay=this.pay
        this.checkOrders=this.orders
        console.log(this.orders)
        this.getAccountList(this.department.id)
      },
      getAccountList(departmentId){
        this.fetch({name:"getAccountList",data:{departmentId}})
          .then(res=>{
            console.log(res)
            this.accountList = res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === param.columns.length - 2) {
            sums[index] = '合计'
            return
          }
          if(index === param.columns.length - 1){
            const values = data.map(item => Number(item[column.property]))
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0).toFixed(2)
            sums[index] += ' 元';
          }else {
            sums[index]=''
          }
        })
        return sums
      },
      btnCreatePay(){//准备创建支付
        this.loading = true
        console.log(this.accountList)
        let account = this.accountList.find(a => a.payType.code === this.selPayType)//获取accountCode
        if(this.checkOrders.length > 1){
          //合并
          console.log(this.currPay)
          let data ={
            subject:this.currPay.subject,
            tradeNo:{tradeNo:this.currPay.id},
            // tradeNo:this.currPay.id,
            payTypeCode:this.selPayType,
            merchantCode:account.code,
            balanceMoney:this.currPay.balanceMoney,
          }
          console.log(data)
          this.createPay(data)
        }else {
          if(this.selPayType === 'balance'){
            // console.log(this.currPay)
            let data ={
              subject:this.currPay.id+'-'+this.currPay.userName+'-'+this.currPay.title,
              // tradeNo:[this.currPay.id],
              tradeNo:{tradeNo:[this.currPay.id]},
              payTypeCode:this.selPayType,
              merchantCode:account.code,
              balanceMoney:this.currPay.balanceMoney
            }
            // console.log(data)
            this.createPay(data)
          }else if(this.selPayType === 'wxpay'){
            let data ={
              subject:'第一个subject',
              tradeNo:{tradeNo:[this.currPay.id]},
              payTypeCode:this.selPayType,
              merchantCode:account.code
            }
            console.log(data)
            // this.createPay(data)
          }else if(this.selPayType === 'wxpay_micropay'){
            let data ={
              subject:'第一个subject',
              tradeNo:{tradeNo:[this.currPay.id]},
              payTypeCode:this.selPayType,
              merchantCode:account.code
            }
            console.log(data)
            this.createPay(data)
          }
        }
      },
      createPay(data){
        console.log(data)
        this.fetch({name:"createPay",data:data})
          .then(res=>{
            this.loading = false
            console.log(res)//res.payNo 支付编码
            this.$confirm('是否支付?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              //去支付
              this.loading = true
              if(res.payType.code ==='wxpay_micropay'){
                res.authodCode=this.getAuthodCode()
              }else if(res.payType.code === "balance"){
                console.log('现金支付——————————————',res)
                this.goToPay(res)
              }
              // console.log('给了一个authodCode',res)
              // this.goToPay(res)
            }).catch(() => {
              this.$emit('cancel')
            })

          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      getAuthodCode(){
        this.$prompt('请扫微信付款码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          let code = 134554270332649947
          return code
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消输入'
          });
        });
      },
      goToPay(pay){
        this.fetch({name:"toPay",data:{payNo:pay.payNo,authodCode:pay.authodCode}})
          .then(res=>{
            console.log(res)
            if(res.data.state === 4){
              this.loading = false
              this.$message({type:'success',message:'支付成功！'})
              this.$emit('cancel')
            }
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
    }
  }
</script>

<style scoped>

</style>
